package org.example.conrtoller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import org.apache.commons.io.IOUtils;
import org.example.Imp.TeacherServiceImp;
import org.example.domain.Teacher;
import org.example.pageParam.CommonData;
import org.example.vo.FileUploadVO;
import org.example.vo.PageVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Controller
public class TeacherController {
    @Autowired
    private TeacherServiceImp teacherServiceImp;
    @RequestMapping("/teacher/tpage")
    public String tpage(Model model){
        //发送这个请求代表的是默认展示teacher页面 默认的一些数据 可以从前端发送过来 也可以后端自己处理
        PageVO pageVo = teacherServiceImp.showTeacherList(null, CommonData.PAGE, CommonData.COUNT);
        model.addAttribute("pageVO",pageVo);
        return "teacher/teacherMainPage";
    }
    /**这个方法和上面那个是一样的 为什么我要写两个 因为前面那个是对整个页面的刷新  这个是局部刷新  因为需要返回不同的模板所以写两个  但是冗余了  不管了*/
    @RequestMapping("/teacher/deleteAll")
    public String deleteAll(Model model){
        //发送这个请求代表的是默认展示teacher页面 默认的一些数据 可以从前端发送过来 也可以后端自己处理
        PageVO pageVo = teacherServiceImp.showTeacherList(null, CommonData.PAGE, CommonData.COUNT);
        model.addAttribute("pageVO",pageVo);
        return "teacher/teacherContextTemplate";
    }

    @RequestMapping("/teacher/select")
    public String select(String filterName,Integer page,Model model){
        PageVO pageVo = null;
        if (page==null){
            //说明可能是过滤查询
            pageVo = teacherServiceImp.showTeacherList(filterName, CommonData.PAGE, CommonData.COUNT);
        }else {
            //可能是分页查询
            pageVo = teacherServiceImp.showTeacherList(filterName,page, CommonData.COUNT);
        }
        ;
        model.addAttribute("pageVO",pageVo);
//        return "teacher/teacherMainPage::#teacherContextFragment";  //不知道为什么这样响应不了对应的片段
        return "teacher/teacherContextTemplate";
    }
    @RequestMapping("/teacher/addView")
    public String addView(Model model){
        model.addAttribute("condition","0");
        return "teacher/teacherAddTemplate";
    }
    @ResponseBody
    @RequestMapping("/teacher/save")
    public String save(String tname){
        try {
            teacherServiceImp.saveOneTeacher(tname);
            return "1";//保存成功
        }catch (Exception e){
            return "0";//保存出现异常  名称或者助记码重复
        }
    }
    @RequestMapping("/teacher/edit")
    public String editView(Long id,Model model){
        model.addAttribute("condition","1");
        model.addAttribute("teacherInfo",teacherServiceImp.selectOneTeacherById(id));
        return "teacher/teacherAddTemplate";
    }
    @ResponseBody
    @RequestMapping("/teacher/submitEdit")
    public String edit(Teacher teacher){
        return teacherServiceImp.editOneTeacher(teacher);
    }
    @ResponseBody
    @RequestMapping("/teacher/deleteOne")
    public void deleteOne(Long id){
        teacherServiceImp.deleteOne(id);
    }
    @ResponseBody
    @RequestMapping("/teacher/deleteAlls")
    public void deleteAll(String ids){
        teacherServiceImp.deleteAll(ids);
    }
    @RequestMapping("/teacher/importAll.html")//做到这里才开始利用这中html规范 返回模板
    public String importAll(Model model){
        model.addAttribute("fileHideValue","file");
        return "teacher/importTemplate";
    }
    @RequestMapping("/teacher/downloadTemplate")
    public ResponseEntity<byte[]> downloadTemplate(){
        InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("downloadTemplate/teacherDemo.xlsx");
        byte[] bytes = null;
        try {
            bytes = new byte[inputStream.available()];
            IOUtils.read(inputStream,bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        HttpHeaders httpHeaders = new HttpHeaders();//这里是为了返回xlsx时 出现下载框 否则默认展示在页面中
        httpHeaders.add("content-disposition","attachment;filename=teacherList.xlsx");
        httpHeaders.add("content-type","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        //content-type中的headValue是在tomcat中web.xml中找到的
        return new ResponseEntity<byte[]>(bytes,httpHeaders,HttpStatus.OK);
    }
    @ResponseBody
    @RequestMapping("/teacher/exportAll")
    public void export(HttpServletResponse response){
        List<Teacher> rows = teacherServiceImp.selectAll();
        // 通过工具类创建writer，默认创建xls格式
        ExcelWriter writer = ExcelUtil.getWriter(true);

        writer.addHeaderAlias("id", "编号");
        writer.addHeaderAlias("tname", "教师姓名");
        writer.addHeaderAlias("mnemonic_code", "姓名");
        writer.addHeaderAlias("create_time", "创建时间");
        writer.addHeaderAlias("update_time", "修改时间");
        writer.setOnlyAlias(true);
// 一次性写出内容，使用默认样式，强制输出标题
        writer.write(rows, true);
//out为OutputStream，需要写出到的目标流

//response为HttpServletResponse对象
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
//test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
        response.setHeader("Content-Disposition","attachment;filename=test.xlsx");
        ServletOutputStream out= null;
        try {
            out = response.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        writer.flush(out, true);
// 关闭writer，释放内存
        writer.close();
//此处记得关闭输出Servlet流
        IoUtil.close(out);
    }
    @ResponseBody
    @RequestMapping("/teacher/fileUpload")
    public FileUploadVO fileUpload(MultipartFile file){
        FileUploadVO fileUploadVO = null;
        try {
            ExcelReader excelReader = ExcelUtil.getReader(file.getInputStream());
            excelReader.addHeaderAlias("教师名称","tname");
            List<Teacher> teacherList = excelReader.readAll(Teacher.class);
            fileUploadVO = teacherServiceImp.saveListTeacher(teacherList);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileUploadVO;
    }
}
